package com.cn.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.service.impl.UserServiceImpl;
import com.cn.utils.MD5Utils;

/**
 * Servlet Filter implementation class AutoLoginFilter
 */
public class AutoLoginFilter implements Filter {

	private UserService us = new UserServiceImpl();
    /**
     * Default constructor. 
     */
    public AutoLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		//第一步，获得autocookie
		Cookie[] cookies = req.getCookies();
		Cookie cookie = null;
		if(cookies!=null){
			for(Cookie c:cookies){
				if("autocookie".equals(c.getName())){
					cookie = c;
				}
			}
		}
		
		if(cookie==null){
			chain.doFilter(request, response);
			return;
		}
		//第二步：获得session中是否有用户登陆的信息
		Object o = req.getSession().getAttribute("user");
		if(o!=null){
			chain.doFilter(request, response);
			return;
		}
		//第三部：给用户登陆
		String[] strs = cookie.getValue().split("@itcast");
		String username = strs[0];
		String password = strs[1];
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		try {
			User u = us.login(user);
			req.getSession().setAttribute("user", u);
		} catch (Exception e) {
			e.printStackTrace();
			cookie.setMaxAge(0);
			resp.addCookie(cookie);
		}
		
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
